package com.bulkmail.sender.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

import com.bulkmail.sender.DataSession;
import com.bulkmail.sender.WriteXMLFile;
import com.bulkmail.sender.WriteXMLOptionFile;

public class SaveAsActionListener implements ActionListener {

	private MainFrame frame;

	public SaveAsActionListener(MainFrame frame) {
		this.frame = frame;
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {

		JFrame saveFrame = new JFrame();
		JFileChooser fileChooser = new JFileChooser(".");
		FileFilter ff = new FileNameExtensionFilter("zip files", "zip");
		fileChooser.addChoosableFileFilter(ff);

		frame.saveMenu.addActionListener(new SaveActionListener(frame));
		frame.repaint();

		saveFrame.getContentPane().add(fileChooser);

		int result = fileChooser.showSaveDialog(null);

		switch (result) {
		case JFileChooser.APPROVE_OPTION:
			File file = fileChooser.getSelectedFile();
			try {
				String shortname = file.getName().substring(0,
						file.getName().indexOf('.'));
				String name = file.getAbsolutePath().substring(0,
						file.getAbsolutePath().indexOf('.'));
				FileOutputStream fos = new FileOutputStream(
						file.getAbsolutePath());
				ZipOutputStream zos = new ZipOutputStream(fos);

				DataSession.setZipPath(file.getAbsolutePath());
				DataSession.setSaved(true);

				DataSession dataSession = new DataSession();
				dataSession.setNrEmails(Integer
						.valueOf(frame.noOfEmailTextField.getText()));
				dataSession.setSeconds(Integer
						.valueOf(frame.timeBetweenTextField.getText()));

				dataSession.setSmtp(frame.smtpRadioButton.isSelected());
				dataSession.setExs(frame.exchangeRadioButton.isSelected());
				dataSession.setAddCounter(frame.counterCheckBox.isSelected());
				dataSession.setAddRandomSubject(frame.randomCheckBox
						.isSelected());

				dataSession.setAttachPath(frame.attachmentTextField.getText());
				dataSession.setServer(frame.serverTextField.getText());
				dataSession.setPort(frame.portTextField.getText());
				dataSession.setUsername(frame.userTextField.getText());
				dataSession.setPassword(new String(frame.passwordField
						.getPassword()));

				dataSession.setFrom(frame.fromTextField.getText());
				List<String> temp = new ArrayList<String>();
				String[] toMany = frame.toTextField.getText().split(";");
				for (int i = 0; i < toMany.length; i++) {
					temp.add(toMany[i]);
				}
				dataSession.setTo(temp);
				dataSession.setSubject(frame.subjectTextField.getText());
				dataSession.setMessage(frame.messageArea.getText());

				String fileFullPath1 = name + "_mail.xml";
				String fileFullPath2 = name + "_opt.xml";

				DataSession.setMailXml(fileFullPath1);
				DataSession.setOptXml(fileFullPath2);

				WriteXMLFile writeSession = new WriteXMLFile(dataSession,
						fileFullPath1);
				WriteXMLOptionFile writeOptions = new WriteXMLOptionFile(
						dataSession, fileFullPath2);

				writeSession.writeXML();
				writeOptions.writeXMLOptionFile();

				String file1Name = fileFullPath1.substring(fileFullPath1
						.indexOf('/'));
				String file2Name = fileFullPath2.substring(fileFullPath2
						.indexOf('/'));

				addToZipFile(file1Name, zos);
				addToZipFile(file2Name, zos);

				zos.close();
				fos.close();

			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			break;
		case JFileChooser.CANCEL_OPTION:
			System.out.println("Cancel or the close-dialog icon was clicked");
			break;
		case JFileChooser.ERROR_OPTION:
			System.out.println("Error");
			break;
		}

		saveFrame.setVisible(true);
		saveFrame.pack();

	}

	public static void addToZipFile(String fileName, ZipOutputStream zos)
			throws FileNotFoundException, IOException {

		File file = new File(fileName);
		System.out.println("Writing '" + file.getName() + "' to zip file");
		FileInputStream fis = new FileInputStream(file);

		ZipEntry zipEntry = new ZipEntry(file.getName());
		zos.putNextEntry(zipEntry);

		byte[] bytes = new byte[1024];
		int length;
		while ((length = fis.read(bytes)) >= 0) {
			zos.write(bytes, 0, length);
		}

		zos.closeEntry();
		fis.close();
	}
}
